import clone from '@/lib/clone';
import {ModuleOptions, StoreOptions} from 'vuex';
import localStorageApi from '@/api/localStorageApi';


//state
const state = () => ({
  recordList: [] as RecordItem[],
  localStorageKeyName: 'recordList'
});

// getters
const getters = {
  fetchRecords(store: RecordStore) {
    localStorageApi.getStore(store.localStorageKeyName, store);
    const value = window.localStorage.getItem(store.localStorageKeyName);
    store.recordList = JSON.parse(value && value !== 'undefined' ? value : '[]');
    return store.recordList;
  },
};
// actions
const actions = {};

// mutations
const mutations = {
  // store:RecordStore
  setRecordList(store: RecordStore, recordList: RecordItem[]) {
    store.recordList = recordList;
  },
  createRecord(store: RecordStore, record: RecordItem) {
    const record2: RecordItem = clone(record);
    record2.createdAt = new Date();
    store.recordList.push(record2);
    this.saveRecords(store);
  },
  saveRecords(store: RecordStore) {
    window.localStorage.setItem(store.localStorageKeyName, JSON.stringify(store.recordList));
  }
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
};
